package com.sixth.controller;

import com.sixth.bean.MarketStorage;

import com.sixth.bean.common.BasePageInfo;
import com.sixth.bean.common.BasePageInfoVo;
import com.sixth.bean.common.BaseRespVo;
import com.sixth.bean.common.BaseResultVo;
import com.sixth.constant.Constant;
import com.sixth.constant.PropertiesConstant;
import com.sixth.service.StorageService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author qys
 * @Description
 * @date 2022/9/7 16:19
 */
@RestController
@RequestMapping("admin/storage")
public class AdminStorageController {
    @Autowired
    StorageService storageService;
    @Autowired
    PropertiesConstant propertiesConstant;
    static String wxStorageFetch = "/wx/storage/fetch/";
    // http://localhost:8083;zxy新增字符串
    static String httpIpPort = "http://"+Constant.SERVER_IP + ":" + Constant.SERVER_PORT;

    /**
     *
     * @author qys
     * @date 2022/9/7 16:23
     * @return BaseRespVo
     */
    @RequiresPermissions(value = {"admin:storage:create"},logical = Logical.OR)
    @PostMapping("create")
    public BaseRespVo adminStorageCreate(MultipartFile file) {
        // 参数封装
        long size = file.getSize();
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        MarketStorage marketStorage = new MarketStorage();
        // marketStorage.setId(100);
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setName(originalFilename);
        marketStorage.setType(contentType);
        marketStorage.setSize(((int) size));
        marketStorage.setDeleted(Constant.EXIST);

        // 随机生成文件名
        UUID uuid = UUID.randomUUID();

        int index = originalFilename.lastIndexOf(".");
        String key = new StringBuffer().append(uuid).append(originalFilename.substring(index)).toString();
        marketStorage.setKey(key);
        // url拼接
        marketStorage.setUrl(wxStorageFetch + key);
        MarketStorage res = storageService.adminStorageCreate(marketStorage);
        String url = "http://" + Constant.SERVER_IP + ":" + Constant.SERVER_PORT + wxStorageFetch + key;
        marketStorage.setUrl(url);
        marketStorage.setDeleted(null);
        // 文件下载
        File directory = new File(propertiesConstant.getFileupload());
        // File directory = new File(PropertiesConstant.fileupload);
        // File directory = new File("c:\\static\\");
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File uploadFile = new File(directory, key);
        // TODO: 文件过大会报异常
        try {
            file.transferTo(uploadFile);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return BaseRespVo.ok(res);
    }

    /**
     * @since 2022/09/07 16:30
     * @author zhaoxiangyang
     */
    @RequiresPermissions(value = {"admin:storage:list"},logical = Logical.OR)
    @RequestMapping("list")
    // public BaseRespVo storageList(Integer page,Integer limit,String sort,String order){
    public BaseRespVo list(String key, String name, BasePageInfo info){
        //key精确查询，名模糊查询，分页降序查询；返回data：分页信息，详情列表
        BasePageInfoVo<MarketStorage> marketStorageBasePageInfoVo = storageService.query(key,name,info);
        return BaseRespVo.ok(marketStorageBasePageInfoVo);
    }
    @RequiresPermissions(value = {"admin:storage:update"},logical = Logical.OR)
    @RequestMapping("update")
    public BaseRespVo update(@RequestBody MarketStorage oldMarketStorage){
        //market_storage数据库url列没有httpIpPort----http://localhost:8083;请求信息响应信息包含它；
        String url =oldMarketStorage.getUrl();
        oldMarketStorage.setUrl(url.replace(httpIpPort,""));
        MarketStorage marketStorage = storageService.update(oldMarketStorage);
        if(marketStorage == null){
            return BaseRespVo.invalidData();
        }
        marketStorage.setUrl(httpIpPort + marketStorage.getUrl());
        return BaseRespVo.ok(marketStorage);
    }
    @RequiresPermissions(value = {"admin:storage:delete"},logical = Logical.OR)
    @RequestMapping("delete")
    public BaseResultVo delete(@RequestBody MarketStorage deleteMarketStorage){
        deleteMarketStorage.setUrl(deleteMarketStorage.getUrl().replace(httpIpPort,""));
        int code = storageService.delete(deleteMarketStorage);
        if(code != Constant.OK){
            return new BaseResultVo(Constant.NON,"删除失败");
        }
        return BaseResultVo.ok();
    }
}
